#!/bin/bash
# This script is released under the GNU General Public License 3.0
# Check the COPYING file included with this distribution

# template for menus which call sub-scripts

# location of other scripts to source
readonly SHAREDIR="$(dirname ${0})" || exit $?

# source common variables, functions and error handling
source "${SHAREDIR}"/common.sh || exit $?

#####################
## begin execution ##

NEWSELECTION=
SELECTION='0'
RETSUB=

while true; do

	NEWSELECTION="$(show_dialog --default-item "${SELECTION}" \
		--menu "Some text" \
		0 0 0 "${MENU_ITEMS[@]}")" || exit $?

	# Alternative to direct exit
	#
	# NEWSELECTION="$(show_dialog --default-item "${SELECTION}" \
	#	--menu "Some text" \
	#	0 0 0 "${_MENU_ITEMS[@]}")" || exit $?
	# RETSUB=$?
	# if [ "${RETSUB}" -ne "0" ]; then
	#	show_dialog --yesno "Abort ....?" 6 40 && exit "${RETSUB}"
	# fi

	# call subscript by selected item
	case "${NEWSELECTION}" in
		'0')
			# call sub script/function
			subscript
			RETSUB=$?
			;;
		'DONE')
			# end this, if needed print some result to STDOUT now
			exit 0
			;;
		*)
			echo "ERROR: Unexpected response '${NEWSELECTION}' in $(basename $0)" 1>&2
			exit 1
			;;
	esac

	# handle errors from sub-script/functions using a common utility function
	if ! catch_menuerror "$(basename $0)" "${NEWSELECTION}" "${RETSUB}"; then
		# no error in sub-script
		# do something, for example: increment selected item
		SELECTION="$((NEWSELECTION+1))" || exit $?
		# or SELECTION="DONE" || exit $?
	fi

done
